package com.lagou.demo.interceptors;

import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.interceptors.HandlerInterceptor;
import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Handler handler) throws Exception {
        Security security = null;
        if (handler.getController().getClass().isAnnotationPresent(Security.class)) {
            security = handler.getController().getClass().getDeclaredAnnotation(Security.class);
        }
        if (handler.getMethod().isAnnotationPresent(Security.class)) {
            security = handler.getMethod().getAnnotation(Security.class);
        }
        if (security != null) { // 开启了权限校验
            if(security.value().length > 0) {
                String loginUser = req.getParameter("username");
                for (String s : security.value()) {
                    if (s.equals(loginUser)) {
                        return true;
                    }
                }
            }
            return false;
        } else { // 没有权限校验
            return true;
        }
    }
}
